<template>
  <div class="add_goods_box">
    <MBX level1="商品管理" level2="商品列表">

      <template v-slot:extra>
         <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </template>
    </MBX>
    <el-card class="mt15">
      <el-alert
        class="mt15"
        :closable="false"
        title="添加商品信息"
        type="info"
        center
        show-icon
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        class="mt15"
        :active="activeName * 1"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addGoodsForm">
        <!-- Tab栏 -->
        <el-tabs
          class="mt15"
          v-model="activeName"
          @tab-click="handleClick"
          :before-leave="beforeLeave"
          tab-position="left"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>

            <el-form-item label="商品重量">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>

            <el-form-item label="商品数量">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类">
              <span
                >选中的商品分类：{{ checkedCateArr }}---当前分类id:{{
                  currentCateId
                }}</span
              >
              <el-cascader
                v-model="checkedCateArr"
                :options="goodscateData"
                :props="defaultProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 动态参数 -->
            <el-form-item
              :label="item1.attr_name"
              :key="item1.attr_id"
              v-for="item1 in manyParams"
            >
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox
                  v-for="(item2, index) in item1.attr_vals"
                  :label="item2"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParams"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <!-- 
              文件上传参数说明：
              action：文件上传时的服务器地址
              headers:配置请求头信息，咱们这里只配置一个token
              on-success:上传成功时的钩子函数
              on-remove:删除上传图片时钩子函数
             -->
            <el-upload
              class="upload-demo"
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headers"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <el-form-item>
                <!-- 富文本编辑器 -->
              <quill-editor v-model="addGoodsForm.goods_introduce" />
              <el-button type='primary' class="mt15" @click='addGoodsOk'>添加商品</el-button>
            </el-form-item>

          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: "addGoods",
  data() {
    return {
      //配置上传的请求头信息
      headers: {
        Authorization: sessionStorage.getItem("token"),
      },
      //商品分类配置项
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      //已选中的商品分类数组
      checkedCateArr: [],
      //商品分类数据源
      goodscateData: [],
      addGoodsForm: {
        //商品名称
        goods_name: "",
        //以为','分割的分类列表
        goods_cat: "",
        //价格
        goods_price: 0,
        //商品数量
        goods_number: 0,
        //商品重量
        goods_weight: 0,
        //商品介绍,富文本
        goods_introduce: "",
        //商品上传图片路径数组[{pic:''},{pic:''},{pic:''}]
        pics: [],
        //attrs即包括动态参数也包括静态属性
        attrs: [],
      },
      activeName: "0",
      //动态参数
      manyParams: [],
      //静态参数
      onlyParams: [],
    };
  },
  created() {
    this.getGoodsCateList();
  },
  methods: {
    //确定向后台添加商品信息
   async addGoodsOk() {
      //1.处理分类数组，转换为以逗号分隔的字符串
        this.addGoodsForm.goods_cat=this.checkedCateArr.join(',')

      //2.将动态参数和静态属性合并，赋值给attrs
      //第一步：使用lodash中的cloneDeep实现深拷贝，解决对象之间相互影响的问题
       let dtParams=_.cloneDeep(this.manyParams)
      
       dtParams=dtParams.map(item=>{
         return {
            "attr_id":item.attr_id,
            "attr_value":item.attr_vals.join(',')
         }
       })

        console.log('dtParams:',dtParams)
      //第二步：处理静态参数
       let jtParams=_.cloneDeep(this.onlyParams)
        jtParams=jtParams.map(item=>{
         return {
            "attr_id":item.attr_id,
            "attr_value":item.attr_vals
         }
       })

      //第三步：合并动态和静态参数
      let mergeParams=[...dtParams,...jtParams]
      //第四步：将合并后的动静参数赋值给attrs
      this.addGoodsForm.attrs=mergeParams
      //第五步：调用接口传递给后台
      let addGoodsForm=_.cloneDeep(this.addGoodsForm)
      await this.$API.addGoodsAPI(addGoodsForm)
      //第六步：路由中转到商品列表页
      this.$router.push('/goods')
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview() {},
    //删除图片是回调
    handleRemove(file) {
      console.log("删除上传图片时的回调:", file);
      //获取要删除的图片路径
      const temp_path = file.response.data.tmp_path;
      //通过findIndex方法找出要删除的元素在上传成功数组中的下标
      const index = this.addGoodsForm.pics.findIndex((item) => {
        return item.pic === temp_path;
      });

      //删除数组中的图片元素
      this.addGoodsForm.pics.splice(index, 1);
    },
    //成功上传时的回调
    handleSuccess(res) {
      console.log("上传图片成功时的回调", res);
      //[{pic:''},{pic:''},{pic:''}]

      //生成图片上传的对象
      let picObj = { pic: res.data.tmp_path };
      //再push给pics
      this.addGoodsForm.pics.push(picObj);

      console.log("要上传的数组：", this.addGoodsForm.pics);
    },
    //监听tab切换之前
    beforeLeave(newActive, oldActive) {
      console.log("newActive", newActive);
      console.log("oldActive:", oldActive);
      if (oldActive === "0" && this.checkedCateArr.length < 3) {
        this.$message({
          message: "您必须选择完三级分类后，才能进行下一步的选择",
          type: "error",
        });
        return false;
      }
    },
    //商品分类级联选择器改变时触发
    handleChange() {
      console.log("商品分类级联选择器改变时触发");
    },
    async handleClick() {
      console.log("我是第几个：", this.activeName);
      if (this.activeName === "1") {
        //渲染动态参数，传'many'
        const res = await this.$API.getGoodsParamsAPI(this.currentCateId);

        //将动态参数转换成数组
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.split(","); 
        });

        console.log("获取到的动态参数：：：：", res);
        this.manyParams = res;
      } else if (this.activeName === "2") {
        //渲染静态参数,传'only'
        const res = await this.$API.getGoodsParamsAPI(
          this.currentCateId,
          "only"
        );
        console.log("获取到的静态属性：：：：", res);
        this.onlyParams = res;
      }
    },
    async getGoodsCateList() {
      const res = await this.$API.goodsCateListAPI();
      console.log("商品分类", res);
      this.goodscateData = res;
    },
  },
  computed: {
    currentCateId() {
      return this.checkedCateArr[this.checkedCateArr.length - 1];
    },
  },
};
</script>

<style lang="scss" scoped>
.add_goods_box ::v-deep .el-step__title {
  font-size: 14px;
}

::v-deep .el-form-item__label {
  width: 100%;
  text-align: left;
}

::v-deep .ql-container {
  height: 300px;
}
</style>
